<template>
  <view class="container">
    <view class="header">
      <text @click="goBack" class="iconfont icon-back"></text>
      <text class="title">{{ isEditMode ? '编辑任务' : '新建任务' }}</text>
      <text @click="saveTask" class="save-btn">保存</text>
    </view>
    
    <view class="form-container">
      <view class="form-item">
        <text class="label">任务标题</text>
        <input 
          type="text" 
          placeholder="请输入任务标题" 
          v-model="taskTitle"
          maxlength="30"
          @input="validateInput">
      </view>
      
      <view class="form-item">
        <text class="label">任务描述</text>
        <textarea 
          placeholder="请输入任务描述（选填）" 
          v-model="taskDescription"
          maxlength="100"
          auto-height>
        </textarea>
      </view>
      
      <view class="form-item">
        <text class="label">任务分类</text>
        <view class="tag-selector">
          <view 
            class="tag-item" 
            :class="{selected: taskTag === 'work'}" 
            @click="setTaskTag('work')">
            <text class="iconfont icon-work"></text>
            <text>工作</text>
          </view>
          <view 
            class="tag-item" 
            :class="{selected: taskTag === 'study'}" 
            @click="setTaskTag('study')">
            <text class="iconfont icon-study"></text>
            <text>学习</text>
          </view>
          <view 
            class="tag-item" 
            :class="{selected: taskTag === 'life'}" 
            @click="setTaskTag('life')">
            <text class="iconfont icon-life"></text>
            <text>生活</text>
          </view>
        </view>
      </view>
      
      <view class="form-item">
        <text class="label">预计时长</text>
        <view class="time-selector">
          <view class="time-unit">
            <text class="unit-label">时</text>
            <picker mode="selector" :range="hoursRange" @change="onHourChange" :value="selectedHour">
              <view class="picker">{{ hoursRange[selectedHour] }}</view>
            </picker>
          </view>
          <view class="time-separator">:</view>
          <view class="time-unit">
            <text class="unit-label">分</text>
            <picker mode="selector" :range="minutesRange" @change="onMinuteChange" :value="selectedMinute">
              <view class="picker">{{ minutesRange[selectedMinute] }}</view>
            </picker>
          </view>
          <view class="time-separator">:</view>
          <view class="time-unit">
            <text class="unit-label">秒</text>
            <picker mode="selector" :range="secondsRange" @change="onSecondChange" :value="selectedSecond">
              <view class="picker">{{ secondsRange[selectedSecond] }}</view>
            </picker>
          </view>
        </view>
      </view>
    </view>
    
    <view v-if="isEditMode" class="delete-btn" @click="confirmDeleteTask">
      <text class="iconfont icon-delete"></text>
      <text>删除任务</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getTask, addTask, updateTask, deleteTask } from '@/utils/storage.js'

const taskId = ref('')
const taskTitle = ref('')
const taskDescription = ref('')
const taskTag = ref('work')
const selectedHour = ref(0)
const selectedMinute = ref(25)
const selectedSecond = ref(0)
const isEditMode = ref(false)
const hoursRange = ref([])
const minutesRange = ref([])
const secondsRange = ref([])
const isFormValid = ref(false)

onMounted(() => {
  // 初始化时间选择器范围
  for (let i = 0; i <= 23; i++) {
    hoursRange.value.push(i.toString())
  }
  
  for (let i = 0; i <= 59; i++) {
    minutesRange.value.push(i.toString())
  }
  
  for (let i = 0; i <= 59; i++) {
    secondsRange.value.push(i.toString())
  }
  
  const options = getCurrentPages()[getCurrentPages().length - 1].options
  if (options.id) {
    taskId.value = options.id
    isEditMode.value = true
    loadTask()
  }
})

const loadTask = async () => {
  if (!taskId.value) return
  
  const task = await getTask(taskId.value)
  if (task) {
    taskTitle.value = task.title || ''
    taskDescription.value = task.description || ''
    taskTag.value = task.tag || 'work'
    
    // 计算时分秒
    const duration = task.duration || 1500 // 默认25分钟
    selectedHour.value = Math.floor(duration / 3600)
    selectedMinute.value = Math.floor((duration % 3600) / 60)
    selectedSecond.value = duration % 60
    
    validateInput()
  }
}

const setTaskTag = (tag) => {
  taskTag.value = tag
}

const onHourChange = (e) => {
  selectedHour.value = e.detail.value
}

const onMinuteChange = (e) => {
  selectedMinute.value = e.detail.value
}

const onSecondChange = (e) => {
  selectedSecond.value = e.detail.value
}

const validateInput = () => {
  isFormValid.value = taskTitle.value.trim().length > 0
}

const saveTask = async () => {
  if (!isFormValid.value) {
    uni.showToast({
      title: '请输入任务标题',
      icon: 'none'
    })
    return
  }
  
  // 计算总秒数
  const totalSeconds = 
    parseInt(selectedHour.value) * 3600 + 
    parseInt(selectedMinute.value) * 60 + 
    parseInt(selectedSecond.value)
  
  const taskData = {
    title: taskTitle.value.trim(),
    description: taskDescription.value.trim(),
    tag: taskTag.value,
    duration: totalSeconds
  }
  
  try {
    if (isEditMode.value) {
      // 更新任务
      taskData.id = taskId.value
      await updateTask(taskData)
    } else {
      // 创建新任务
      await addTask(taskData)
    }
    
    uni.showToast({
      title: isEditMode.value ? '任务更新成功' : '任务创建成功',
      icon: 'success'
    })
    
    setTimeout(() => {
      uni.navigateBack()
    }, 1000)
  } catch (error) {
    console.error('保存任务失败:', error)
    uni.showToast({
      title: '保存任务失败',
      icon: 'none'
    })
  }
}

const confirmDeleteTask = () => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个任务吗？此操作不可撤销。',
    confirmText: '删除',
    confirmColor: '#FF5630',
    success: async (res) => {
      if (res.confirm) {
        try {
          await deleteTask(taskId.value)
          uni.showToast({
            title: '任务已删除',
            icon: 'success'
          })
          
          setTimeout(() => {
            uni.navigateBack()
          }, 1000)
        } catch (error) {
          console.error('删除任务失败:', error)
          uni.showToast({
            title: '删除任务失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

const goBack = () => {
  uni.navigateBack()
}
</script>

<style scoped>
.container {
  padding: 20rpx;
  height: 100vh;
  background-color: #f7f7f7;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
}

.save-btn {
  font-size: 32rpx;
  color: #165DFF;
  padding: 10rpx 20rpx;
}

.form-container {
  margin-top: 40rpx;
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
}

.form-item {
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
}

.form-item:last-child {
  border-bottom: none;
}

.label {
  font-size: 32rpx;
  display: block;
  margin-bottom: 20rpx;
}

input, textarea {
  width: 100%;
  font-size: 32rpx;
}

textarea {
  min-height: 120rpx;
}

.tag-selector {
  display: flex;
  gap: 20rpx;
}

.tag-item {
  flex: 1;
  text-align: center;
  padding: 20rpx 0;
  border-radius: 12rpx;
  border: 2rpx solid #eee;
}

.tag-item.selected {
  border-color: #165DFF;
  background-color: rgba(22, 93, 255, 0.1);
  color: #165DFF;
}

.tag-item text:first-child {
  font-size: 40rpx;
  display: block;
  margin-bottom: 10rpx;
}

.time-selector {
  display: flex;
  align-items: center;
  justify-content: center;
}

.time-unit {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 160rpx;
}

.unit-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.picker {
  font-size: 40rpx;
  font-weight: bold;
  padding: 10rpx 0;
}

.time-separator {
  font-size: 40rpx;
  font-weight: bold;
  padding: 0 20rpx;
}

.delete-btn {
  margin-top: 60rpx;
  text-align: center;
  color: #FF5630;
  font-size: 32rpx;
}

.delete-btn text:first-child {
  margin-right: 10rpx;
}

/* 暗黑模式样式 */
.container.dark {
  background-color: #1c1c1e;
}

.container.dark .form-container,
.container.dark .tag-item {
  background-color: #2c2c2e;
  border-color: #3a3a3c;
}

.container.dark .form-item {
  border-bottom-color: #3a3a3c;
}

.container.dark input,
.container.dark textarea,
.container.dark .label,
.container.dark .picker {
  color: #fff;
}

.container.dark .tag-item.selected {
  border-color: #165DFF;
}

.container.dark .unit-label {
  color: #999;
}
</style>  